#include <stdio.h>

#include <OpenGL/gl.h>

#include "core.h"
#include "image.h"
#include "soil.h"

namespace image {

    void Draw::draw() {
        glEnable(GL_TEXTURE_2D);
        image_->Bind2D();
        double w = image_->width();
        double h = image_->height();
        glPushMatrix();
        glTranslated(x_, y_, 0.0);
        glRotated(r_ * 180 / CONST_PI, 0, 0, 1);
        glBegin(GL_QUADS);
        glTexCoord2d(0.0, 1.0);
        glVertex2d(-w/2, -h/2);
        glTexCoord2d(1.0, 1.0);
        glVertex2d(w/2, -h/2);
        glTexCoord2d(1.0, 0.0);
        glVertex2d(w/2, h/2);
        glTexCoord2d(0.0, 0.0);
        glVertex2d(-w/2, h/2);
        glEnd();
        glDisable(GL_TEXTURE_2D);
        glPopMatrix();
    }
    
    Image::Image() : i(-1) {
    }
    Image::~Image() {
    }

    Image* Image::Load(const char*filename) {
        char t[256];
        snprintf(t, 255, "%s/%s", resource_dir().c_str(), filename);
        Image *result = new Image();
        result->data_ = SOIL_load_image(t, &result->width_, &result->height_, &result->channels_, 0);
        if (!result->data_) return 0;
        result->i = SOIL_create_OGL_texture(result->data_, result->width_, result->height_, result->channels_, 0, 0);
        if (!result->i) return 0;
        return result;
    }

    void Image::Bind2D() {
        glBindTexture(GL_TEXTURE_2D, this->i);
    }

}  // namespace